﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using Agr.CQRS.Domain.Repository;

namespace Agr.CQRS.Domain.Commands
{
    public abstract class CommandHandler
    {
        private IDomainRepository repos;

        [Inject]
        public void SetRepository(IDomainRepository repos)
        {
            this.repos = repos;
        }

        private List<AggregateRoot> affectedObjects = new List<AggregateRoot>();
        protected T GetById<T>(Guid id, int version) where T : AggregateRoot
        {
            var ar = repos.GetById<T>(id, version);
            affectedObjects.Add(ar);
            return ar;
        }

        public void ExecuteCommand(Command command)
        {
            ExecuteInternal(command);
            foreach (var ar in affectedObjects)
                repos.SaveChanges(ar);
            affectedObjects.Clear();
        }

        protected abstract void ExecuteInternal(Command command);
    }

    public abstract class CommandHandler<T> : CommandHandler where T : Command
    {
        protected abstract void ExecuteInternal(T command);
        protected override void ExecuteInternal(Command command)
        {
            ExecuteInternal(command as T);
        }
    }
}
